import redis

import excelDemo


class RedisRanking:
    def __init__(self, host='localhost', port=6379, db=1):
        self.r = redis.Redis(host=host, port=port, db=db)

    def add_score(self, key, member, score):
        """添加/更新分数"""
        return self.r.zadd(key, {member: score})

    def get_rank(self, key, member):
        """获取排名（从小到大，0-based）"""
        return self.r.zrank(key, member)

    def get_reverse_rank(self, key, member):
        """获取逆序排名（从大到小，0-based）"""
        return self.r.zrevrank(key, member)

    def get_range_by_rank(self, key, start, end, with_scores=False):
        """获取指定排名范围的成员（正序）"""
        return self.r.zrange(key, start, end, withscores=with_scores)

    def get_reverse_range_by_rank(self, key, start, end, with_scores=False):
        """获取指定排名范围的成员（逆序）"""
        return self.r.zrevrange(key, start, end, withscores=with_scores)

    def get_score(self, key, member):
        """获取成员分数"""
        return self.r.zscore(key, member)

    def increment_score(self, key, member, amount=1):
        """增加分数"""
        return self.r.zincrby(key, amount, member)

    def get_range_by_score(self, key, min_score, max_score, with_scores=False):
        """获取指定分数范围的成员"""
        return self.r.zrangebyscore(key, min_score, max_score, withscores=with_scores)

    def get_total_members(self, key):
        """获取排行榜总人数"""
        return self.r.zcard(key)


# 使用示例
if __name__ == "__main__":
    ed = excelDemo.FunDemo()
    ed.fun4()

    # ranking = RedisRanking()
    # key = "game:ranking"
    # excelDemo.fun4()
    # # 添加数据
    # ranking.add_score(key, "player1", 100)
    # ranking.add_score(key, "player2", 200)
    # ranking.add_score(key, "player3", 150)
    # ranking.add_score(key, "player4", 300)
    #
    # # 获取玩家2的正序排名（返回2，表示第3名）
    # print(f"Player2的正序排名: {ranking.get_rank(key, 'player2')}")
    #
    # # 获取玩家2的逆序排名（返回1，表示第2名）
    # print(f"Player2的逆序排名: {ranking.get_reverse_rank(key, 'player2')}")
    #
    # # 获取逆序前3名
    # print(f"逆序前3名: {ranking.get_reverse_range_by_rank(key, 0, 2)}")
    #
    # # 获取玩家3的分数并增加50分
    # score = ranking.get_score(key, "player3")
    # print(f"Player3原分数: {score}")
    # ranking.increment_score(key, "player3", 50)
    # print(f"Player3新分数: {ranking.get_score(key, 'player3')}")
    #
    # # 获取分数在100-200之间的玩家
    # print(f"分数在100-200之间的玩家: {ranking.get_range_by_score(key, 100, 200)}")
    #
    # # 获取排行榜总人数
    # print(f"排行榜总人数: {ranking.get_total_members(key)}")